package landyer.study.charsetdetect;

import org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * User: landy
 * Date: 15/3/17
 * Time: 下午5:24
 */
public class ListAllGBK {
    public static final FileFilter JAVA_FILTER = new FileFilter() {
        @Override
        public boolean accept(File file) {
            return file.isDirectory() || file.getName().toLowerCase().endsWith(".java");
        }
    };

    public static void main(String[] args) throws IOException {
        while (doWork() != 0) {

        }
        //showCharset("/Volumes/apple/xiayu/codes/GodServerCharset/src/com/cloudPoint/NetUtil.java");
        //showCharset("/Volumes/apple/xiayu/codes/GodServerCharset/src/com/init/Init.java");
    }

    private static void showCharset(String s) throws IOException {
        String[] strings = new CharsetDetector().detectChineseCharset(new FileInputStream(s));
        System.out.println(Arrays.toString(strings));
    }

    private static int doWork() throws IOException {
        String dir = "/Volumes/apple/xiayu/codes/GodServerCharset";
        File file = new File(dir);
        System.out.println(file.getAbsolutePath());
        List<File> files = new LinkedList<File>();
        collectFiles(file, files);

        System.out.println("file number:" + files.size());
        int flag = 0;
        for (File one : files) {
            String[] charsets = new CharsetDetector().detectChineseCharset(new FileInputStream(one));
            if (needConvert(charsets)) {
                flag++;
                System.out.println(Arrays.toString(charsets) + ":" + one.getAbsolutePath());
                String content = FileUtils.readFileToString(one, "GBK");
                FileUtils.writeStringToFile(one, content, Charsets.UTF_8, false);
            }
        }
        System.out.println("flag :" + flag);
        return flag;
    }

    private static boolean needConvert(String[] charsets) {
        for (String one : charsets) {
            if (Arrays.asList("GB18030", "GB2312", "GBK").contains(one)) {
                return true;
            }
        }
        return false;
    }

    private static void collectFiles(File file, List<File> files) {
        if (file.isDirectory()) {
            for (File one : file.listFiles(JAVA_FILTER)) {
                collectFiles(one, files);
            }
        } else {
            files.add(file);
        }
    }
}
